import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  ClientHomeDocumentType,
  LogoDocumentType,
} from '../schema/ClientHome/home.schema';

import { UserDocumentType } from '../schema/User/user.schema';
import { hashPassword, comparePasswords } from '../utils/Decrypt';

import { sendEmail } from '../utils/Email';
import { AuthService } from 'src/auth/auth.service';

@Injectable()
export class UserService {
  constructor(
    private readonly authService: AuthService,
    @InjectModel('ClientHome')
    private clientHomeModel: Model<ClientHomeDocumentType>,
    @InjectModel('User') private userModel: Model<UserDocumentType>,
    @InjectModel('Logo') private logoModel: Model<LogoDocumentType>,
  ) {}

  async createClientHome(body: any) {
    const clientHome = new this.clientHomeModel(body);
    return clientHome.save();
  }

  async getClientHome() {
    return this.clientHomeModel.find().select('title content');
  }

  //发送邮件

  async toEmail(email: string, code: string) {
    sendEmail(email, code);

    return {
      code: 200,
      msg: '发送成功',
    };
  }

  async createUser(body: any) {
    const { password, code, email, codeCache, username } = body;
    //判断邮箱是否已经注册
    const isExist = await this.userModel.findOne({ email });
  
    if (isExist) {
      return {
        code: 400,
        msg: '邮箱已注册',
      };
    } else {
      //验证码校验
      if (code !== codeCache) {
        return {
          code: 400,
          msg: '验证码错误',
        };
      } else {
        //密码加密
        try {
          const hashedPassword = await hashPassword(password);
          // const hashedPassword = password;
          const user = new this.userModel({ username, hashedPassword, email });
          user.save();
          return {
            code: 200,
            msg: '注册成功',
          };
        } catch (error) {}
      }
    }
  }

  async login(body: any) {
    const { password, username } = body;
    //判断用户是否存在
    const user = await this.userModel.findOne({ username });
    if (!user) {
      return {
        code: 400,
        msg: '用户不存在',
      };
    } else {
      //密码校验
      const isMatch = await comparePasswords(password, user.hashedPassword);
      // const isMatch = password === user.hashedPassword;
      if (isMatch) {
        //登录成功

        const token = await this.authService.generateToken({ id: user._id });

        return {
          code: 200,
          data: {
            msg: '登录成功',
            username,
            token,
            avatar: user.avatar,
            id: user._id,
          },
        };
      } else {
        return {
          code: 400,
          msg: '密码错误',
        };
      }
    }
  }

  async autoLogin(body: any) {
    const { token } = body;
    // console.log(token);

    const decoded = await this.authService.verifyToken(token);
    // console.log(decoded);

    if (decoded) {
      //通过id查找用户
      const user = await this.userModel.findById(decoded.id);

      return {
        code: 200,
        data: {
          msg: '自动登录成功',
          username: user.username,
          avatar: user.avatar,
          id: user._id,
        },
      };
    } else {
      return {
        code: 400,
        msg: '自动登录失败',
      };
    }
  }

  async createLogo(body: any) {
    const logo = new this.logoModel(body);
    return logo.save();
  }

  async getLogo() {
    return this.logoModel.find();
  }

  async updateUser(body: any) {
    const { id, avatar, username } = body;
    //通过id查找用户
    const user = await this.userModel.findById(id);
    //更新头像
    avatar && (user.avatar = avatar);
    //更新用户名
    username && (user.username = username);

    user.save();
    return {
      code: 200,
      msg: '更新成功',
    };
  }

  //获用户数量
  async getUserCount() {
    const count = await this.userModel.countDocuments();
    console.log(count);

    return {
      code: 200,
      data: {
        count,
        msg: 'success',
      },
    };
  }
}
